<?php
namespace app\admin\controller;
use app\admin\model\orderModel;
use app\admin\model\shopModel;
use controller\BasicAdmin;
use think\Db;
use think\Validate;
use Think\Controller;
class Adminshop extends BasicAdmin{
    public $table = 'shop';
    public $picture = 'picture';


    /**
     * 店铺列表
     */
    public function index(){
        $shopModel = new shopModel();
        list($get, $db) = [$this->request->get(), Db::name($this->table)->field('id,username,name,status,bind_mobile,province,type_id,updated_at')];
        $where = '1=1';
        isset($get['username']) && $get['username']!='' ? $where ="name like '%{$get['username']}%' OR username like '{$get['username']}'" :'';
        isset($get['status']) && $get['status'] !='' ? $where .=" AND status={$get['status']}" : '';
        isset($get['role']) && $get['role'] !='' ? $where .=" AND type_id={$get['role']}" : '';

        if(isset($get['province']) and ($get['province'] !='')){
            $area['area_id'] = $get['province'];
            $list['arealist'] = Db::name('area')->where(['ParentId'=>$area['area_id']])->field('ID,ParentId,ShortName')->select();
            if(isset($get['City']) and ($get['Area'] !='')){
                $area['area_id'] = $get['City'];
                $list['citylist'] = Db::name('area')->where(['ParentId'=>$area['area_id']])->field('ID,ParentId,ShortName')->select();
                if(isset($get['Area']) and ($get['Area'] !='')) {
                    $area['area_id'] = $get['Area'];
                }
            }
            $db->where($area);
        }
        $list = parent::_list($db->where($where)->order('created_at DESC')->order(''),1,'','');
        $list['status'] = $shopModel->getStatus();
        $list['type'] = $shopModel->typeList();
        $list['list'] = $shopModel->getTypeName($list['list']);
        $list['list'] = $shopModel->getListTname($list['list']);
        $list['area'] = Db::name('area')->where(['ParentId'=>100000])->field('ID,ParentId,ShortName')->select();

        return $this->fetch('', ['title' => '店铺列表','list'=>$list]);
    }

    /**
     * 编辑列表
     */
    public function edit(){
        $get = $this->request->get();
        $this->title = '店铺编辑';
        $info = Db::name($this->table)->where(['id'=>$get['id']])->find();
        $type  = Db::name('shop_type')->where(['status'=>1])->order('sort DESC')->select();
        $shopModel = new shopModel();
        if($info['thumb']){
        $picurl = Db::name($this->picture)->where(['id'=>$info['thumb']])->value('picurl');//缩略图

            if(!empty($picurl)){
                $info['picurl'] = $picurlImg = $this->imgUrl($picurl);
                $RQcode = $shopModel->rqCode($picurlImg,$info['id']);
            }
            //位置
            if($info['area_id']){
                $info['area_name'] = Db::name('area')->where(['ID'=>$info['area_id']])->value('Name');
            }
        }

        $info['area_list'] = $this->areaList($info['area_id']);
        return $this->fetch('',['title'=>$this->title,'info'=>$info,'type'=>$type]);
    }

    /**
     * @param int $area_id
     * 获取城市相关信息
     */
    public function areaList($area_id=0){
        $data = [];
        $data['Area'] = Db::name('area')->where(['ID'=>$area_id])->field('ID,ParentId,ShortName,LevelType')->find();
        $data['Arealist'] = Db::name('area')->where(['ParentId'=>$data['Area']['ParentId']])->field('ID,ParentId,ShortName,LevelType')->select();

        $data['City'] = Db::name('area')->where(['ID'=>$data['Area']['ParentId']])->field('ID,ParentId,ShortName,LevelType')->find();
        $data['Citylist'] = Db::name('area')->where(['ParentId'=>$data['City']['ParentId']])->field('ID,ParentId,ShortName,LevelType')->select();

        $data['province'] = Db::name('area')->where(['ID'=>$data['City']['ParentId']])->field('ID,ParentId,ShortName,LevelType')->find();
        $data['provincelist'] = Db::name('area')->where(['ParentId'=>$data['province']['ParentId']])->field('ID,ParentId,ShortName,LevelType')->select();

        return $data;
    }

    /**
     * 编辑提交
     */
    public function editPost(){
        $post = $this->request->post();
        $shopinfo = Db::name($this->table)->where(['id'=>$post['id']])->find();
        if(empty($shopinfo))$this->error('数据错误');
        $data['username'] = $post['username'];//账号
        $shopModel = new shopModel();
        $resulePs = $shopModel->passwordEdit($post['password'],$post['id']);//密码
        if(isset($post['cat_ids1']) && $post['cat_ids1'] !=''){
            $cat = explode(',',$post['cat_ids1']);
            if(!empty($cat[2])){
                $data['area_id'] = $cat[2];
            }elseif ($cat[1]){
                $data['area_id'] = $cat[1];
            }else{
                $data['area_id'] = $cat[0];
            }
        }
        $data['tel'] = $post['tel'];
        $data['bind_mobile'] = $post['bind_mobile'];//手机号码
        $data['shophours'] = $post['shophours'];//营业时间
        $data['push'] = $post['push'];//推荐
        $data['description'] = $post['description'];//介绍
        $data['consumption'] = $post['consumption'];//人均消费
        $data['status'] = $post['status'];//状态
        $data['lng'] = $post['lng'];//经度
        $data['lat'] = $post['lat'];//纬度
        $data['thumb'] = $post['pictureid'];//缩略图
        $data['type_id'] = $post['type_id'];
        if(!$data['type_id']){
            $this->error('店铺状态是必填项');
        }
        $resule = Db::name($this->table)->where(['id'=>$post['id']])->update($data);

        if(!empty($resule)){
            //添加钱包
            $id = Db::name($this->table)->order('id desc')->value('id');
            $cdata['type'] =1;
            $cdata['uid'] =$id;
            Db::name('capital')->insert($cdata);
            $this->success('编辑成功','');
        }else{
            $this->error('编辑失败','');
        }

    }

    /**
     * 店铺图片
     */
    public function shopImg(){
        $get = $this->request->get();
        list($get, $db) = [$this->request->get(), Db::name($this->table)];
        $info = $db->where(['id'=>$get['id']])->find();

        if(!empty($info['picture_id'])){
            $where = "id IN ({$info['picture_id']})";
            $info['list'] = Db::name($this->picture)->where($where)->select();
            $info['list'] = $this->imgUrl($info['list'],'picurl');
            $info['id'] = $get['id'];
        };
        return $this->fetch('', ['title' => '店铺图片','list'=>$info]);
    }

    public function detImg(){
        $post = $this->request->post();
        $id = $post['id'];
        $ids = explode(',',$id);
        $value = $post['value'];
        //查询店铺图片
        $picture = Db::name($this->table)->where(['id'=>$value])->value('picture_id');
        $picture = explode(',',$picture);
        $idArr = implode(',',$this->forarr($picture,$ids));
        $re = Db::name($this->table)->where(['id'=>$value])->update(['picture_id'=>$idArr]);

        if(!empty($re)){
            $this->success('删除成功','');
        }else{
            $this->error('删除失败');
        }
    }

    /**
     * @param array $list 原有的id
     * @param array $arr  要删除的id
     *
     */
    public function forarr($list = [],$arr = []){
        foreach ($list as $key=>$val){
            foreach ($arr as $k=>$item){
                if($val === $item){
                   unset($list[$key]);
                }
            }
        }
        return $list;
    }

    /**
     * 逻辑删除店铺
     */
    public function delShop(){
        $get = $this->request->get();
        if($get['id'] == '')$this->error('请求失败');
        $status = Db::name($this->table)->where(['id'=>$get['id']])->value('status');

        if($status === 0){
            $restule = Db::name($this->table)->where(['id'=>$get['id']])->update(['status'=>2]);
            //删除钱包
            Db::name('capital')->where(['type'=>1,'uid'=>$get['id']])->update(['status'=>2]);
        }else{
            $this->error('店铺以上线就不能删除');
        }
        if(!empty($restule)){
            $this->success('删除成功','');
        }else{
            $this->error('店铺已被删除');
        }
    }

    /**
     * 店铺详情
     */

    public function orderShop(){
        $get = $this->request->get();
        $orderModel = new orderModel();
        $list = $orderModel->orderDel($get['id'],0);
    }

    public function edittype(){
        $get = $this->request->get();
        if(empty($get['id']))$this->error('请求失败');
        if(isset($get['type'])&&$get['type']!=''){
            if($get['type']==2){
                $this->table ='shop_item';
            }
        }
        $status = Db::name($this->table)->where(['id'=>$get['id']])->value('status');
        if($status == 1){//正常
          $result  = Db::name($this->table)->where(['id'=>$get['id']])->update(['status'=>2]);
        }else if($status == 2){//删除
            $result = Db::name($this->table)->where(['id'=>$get['id']])->update(['status'=>1]);
        }else{//审核
            $result = Db::name($this->table)->where(['id'=>$get['id']])->update(['status'=>1]);
        }
        if(!empty($result)){
            echo json_encode(['code'=>200,'msg'=>'修改成功']);
        }else{
            echo json_encode(['code'=>200,'msg'=>'修改失败']);
        }
    }

    /**
     * 添加店铺
     */
    public function add(){
        $list = Db::name('area')->where(['ParentId'=>100000])->field('ID,ParentId,ShortName')->select();
        $type = Db::name('shop_type')->where(['status'=>1])->order('sort DESC')->field('id,name')->select();
        return $this->fetch('', ['title' => '添加店铺','list'=>$list,'type'=>$type]);
    }

    /**
     * 添加店铺环境图片
     */
    public function addimg(){
        return $this->fetch('', ['title' => '添加店铺图片']);
    }

    /**
     * 添加店铺
     */
    public function addshop(){
        $this->vadate();
        $post = $this->request->post();
        $data['created_at'] =date('Y-m-d H:i:s');
        $data['name'] = $post['name'];//店铺名称
        $data['username'] = $post['username'];//用户名
        $data['password'] = MD5($post['password']);//密码
        $data['tel'] = $post['tel'];//联系电话
        $data['bind_mobile'] = $post['bind_mobile'];//老板电话
        $data['shophours'] = $post['shophours'];//营业时间
        $data['push'] = $post['push'];//推荐
        $data['description'] = $post['description'];//介绍
        $data['consumption'] = $post['consumption'];//人均消费
        $data['address'] = $post['address'];//详细地址
        $data['status'] = 0;
        $data['thumb'] = $post['img'];//缩虐图
        $data['type_id'] = $post['type_id'];//类别
        if(!$data['type_id'] ){
            $this->error('店铺类别必填');
        }
        if($post['province'] !=''){
            $data['area_id'] = $post['province'];
            $data['province'] = $post['province'];
        }
        if($post['City'] !=''){
            $data['area_id'] = $post['City'];
            $data['city'] = $post['City'];
        }
        if($post['Area'] !=''){
            $data['area_id'] = $post['Area'];
        }
        $data['lng'] = $post['lng'];
        $data['lat'] = $post['lat'];

        $result = Db::name($this->table)->insert($data);
        if($result){
            $this->success('添加成功','');
        }else{
            $this->error('添加失败','');
        }
    }
    protected function vadate(){
        $post = $this->request->post();
        $validate = new Validate([
            'name'          =>  'require|max:20',
            'username'      =>  'require|max:15',
            'password'      =>  'require|max:12',
            'tel'           =>  'require|max:12',
            'bind_mobile'   =>  'require|max:12',
            'shophours'     =>  'require',
            'consumption'   =>  'require',
        ]);
        $data = [
            'name'  => $post['name'],
            'username' => $post['username'],
            'password' => $post['password'],
            'tel' => $post['tel'],
            'bind_mobile' => $post['bind_mobile'],
            'shophours' => $post['shophours'],
            'consumption' => $post['consumption'],
        ];

        $validate->message('name','店铺名称过长');
        $validate->message('username','店铺账号过长');
        $validate->message('password','密码过长');
        $validate->message('tel','电话格式不对');
        $validate->message('bind_mobile','电话格式不对');
        $validate->message('shophours','营业时间必填');
        $validate->message('consumption','人均消费必填');

        if (!$validate->check($data)) {
            $code = $validate->getError();
            $this->error($validate->getError());
        }
    }
    public function cities(){
        $shopModel = new shopModel();
        $list = $shopModel->Cities();
        echo json_encode($list,true);
    }

    /**
     * 店铺服务
     */
    public function shopService(){
        list($get, $db) = [$this->request->get(), Db::name('shop_item')->alias('a')->field('a.name,a.status,a.id,a.soldnum,a.created_at,a.cid')];
        $where = '1=1';
        if(isset($get['id'])&&$get['id'] != ''){
            $db->where('a.sid',$get['id']);
        }
        $list = parent::_list($db->where($where),1,'','');
        $list['shopname']= Db::name('shop')->where(['id'=>$get['id']])->value('name');
        $shupModel = new shopModel();
        $list['list']= $shupModel->shopclass($list['list']);
        return $this->fetch('', ['title' => '服务列表','list'=>$list]);
    }

    /**
     * 店铺服务编辑
     */
    public function serviceEdit(){
        $get = $this->request->get();
        $info = Db::name('shop_item')->where(['id'=>$get['id']])->find();
        $info['sname']= Db::name('shop')->where(['id'=>$info['sid']])->value('name');
        $info['class'] = Db::name('shop_class')->where(['sid'=>$info['sid']])->field('id,name')->select();
        //缩略图
        $picurl = Db::name($this->picture)->where(['id'=>$info['pictureid']])->value('picurl');//缩略图
        $info['img'] = $picurlImg = $this->imgUrl($picurl);
        return $this->fetch('', ['title' => '店铺服务编辑','info'=>$info]);
    }
    /**
     * 店铺提现
     */
    public function shopCapital(){
        list($get, $db) = [$this->request->get(), Db::name('shop_capital_put')->alias('a')->join('shop b','a.shop_id=b.id','LEFT')->field('a.shop_id,a.id,a.money,a.service_charge,a.real_money,a.status,a.put_type,a.created_at,b.name')];
        $where = '1=1';
        if(isset($get['id'])&&$get['id'] != ''){
            $db->where('shop_id',$get['id']);
        }
        if (isset($get['created_at']) && $get['created_at'] !== '') {
            list($start, $end) = explode(' - ', $get['created_at']);
            $db->whereBetween('a.created_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
        }

        $list = parent::_list($db->where($where),1,'','');

        //提现状态
        $status = [0=>'待处理',1=>'处理中',2=>'提现成功',3=>'提现失败'];
        $put_type = [1=>'支付宝',2=>'微信',3=>'银行卡'];

        foreach ($list['list'] as $k=>$v){
            $list['list'][$k]['statusName'] = $status[$v['status']];
            $list['list'][$k]['put_type_name'] = $put_type[$v['put_type']];
        }
        return $this->fetch('', ['title' => '服务列表','list'=>$list]);
    }

    /**
     * 商家收益
     */
    public function shopProfit(){
        list($get, $db) = [$this->request->get(), Db::name('shop_profit')->alias('a')->join('t_order b','a.order_id=b.id','LEFT')];
        $where = '1=1';
        if(isset($get['id'])&&$get['id'] != ''){
            $db->where('a.shop_id',$get['id']);
            $name = Db::name('shop')->where(['id'=>$get['id']])->value('name');
        }
        $list = parent::_list($db->where($where),1,'','');

        $list['shopname'] = $name;


        return $this->fetch('', ['title' => '商家收益','list'=>$list]);
    }

    /**
     * 获取地区
     */
    public function getarea(){
        header("Content-Type: text/html;charset=utf-8");
        list($get, $db) = [$this->request->get(), Db::name('area')];
        $list = $db->where(['ParentId'=>$get['pid']])->field('ID,ParentId,ShortName')->select();
        echo json_encode($list);die;
    }

}